<?php
/**
 * Created by PhpStorm.
 * User: 吕金鹏
 * Date: 2021/5/27
 * Time: 8:46 上午
 */

namespace app\index\controller;
use think\Db;
use think\facade\Request;

class Inorder extends Base
{
    public function index(){
        $list =Db::name("inorder")->where("if_del",0)->order("addtime desc")->paginate(15)->each(function($item){
            $item['c_name'] = Db::name("warehouse")->where('id',$item['cid'])->find()['name'];
            return $item;
        });

        $this->assign("page",$list->render());
        $this->assign("list",$list);
        return $this->fetch();
    }
    //创建入库单
    public function addorder(){
        if(Request::isPost()){
            $data = input("post.");
            //添加入库单
            $inorder_data['addtime'] = time();
            $inorder_data['if_del'] = 0;
            $inorder_data['status'] = 1;
            $inorder_data['sn'] = $data["order"];
            $inorder_data['cid'] = $data["cid"];

            $inorder_data['admin_id'] = $this->admin['id'];
            $inorder_data['admin_name'] = $this->admin['rel_name'];
            // 启动事务
            Db::startTrans();
            try {
                $id = Db::name("inorder")->insertGetId($inorder_data);
                foreach($data['pg_id'] as $key=>$val){
                    //修改入库单商品数量记录数量
                    Db::name("procure_goods")->where("id",$val)->setDec("innum",$data["num"][$key]);
                    //添加入库单商品
                    $goods_info = Db::name("goods")->where("id",$data['gid'][$key])->find();
                    $in_goods_data = [];
                    $in_goods_data['time'] = time();
                    $in_goods_data['gid'] = $data['gid'][$key];
                    $in_goods_data['pg_id'] = $data['pg_id'][$key];
                    $in_goods_data['num'] = $data['num'][$key];
                    $in_goods_data['name'] = $goods_info['name'];
                    $in_goods_data["inorder_id"] = $id;
                    $in_goods_data["ware_id"] = $data["ware_id"][$key];
                    $in_goods_data["inprice"] = $data["inprice"][$key];
                    Db::name("inorder_goods")->insert($in_goods_data);
                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['code'=>0,"msg"=>'网络延时,稍后姿势']);
            }

            return json(['code'=>1,'msg'=>'添加成功']);
        }
        //查看所有未完成入库采购单
        $order = Db::name("procure")->where("if_del",0)->where("status",3)->select();
        foreach ($order as &$v) {
            $goods =  Db::name("procure_goods")->where("oid",$v['id'])->where("innum",'>',0)->select();

            foreach($goods as &$m){
                $info = Db::name("goods")->where("id",$m['gid'])->find();
                $m['ware'] = Db::name("warehouse")->where("id",$m['ware_id'])->find()['name'];
                $m['unit'] = $info['unit'];
                $m['name'] = $info['name'];
                $m['specs'] = $info['specs'];
                $m['num'] = $m["innum"];
            }
            $v['goods'] = $goods;
        }
        //选择供应商
        $gongying = Db::name("gongying")->where("if_del",0)->where("status",1)->select();
        $sn = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        $this->assign('sn',$sn);
        $this->assign("gongying",$gongying);
        $this->assign("order",$order);
        return $this->fetch();
    }
    //编辑商品
    public function changegoods(){
        if(Request::isPost()){
            $data = input("post.");
            //添加入库单
            $inorder_data['addtime'] = time();
            $inorder_data['if_del'] = 0;
            $inorder_data['status'] = 1;
            $inorder_data['sn'] = $data["order"];
            $inorder_data['cid'] = $data["cid"];

            // 启动事务
            Db::startTrans();
            try {
                $id = Db::name("inorder")->insertGetId($inorder_data);
                foreach($data['pg_id'] as $key=>$val){
                    //修改入库单商品数量记录数量
                    Db::name("procure_goods")->where("id",$val)->setDec("innum",$data["num"][$key]);
                    //添加入库单商品
                    $goods_info = Db::name("goods")->where("id",$data['gid'][$key])->find();
                    $in_goods_data = [];
                    $in_goods_data['time'] = time();
                    $in_goods_data['gid'] = $data['gid'][$key];
                    $in_goods_data['pg_id'] = $data['pg_id'][$key];
                    $in_goods_data['name'] = $goods_info['name'];
                    $in_goods_data["inorder_id"] = $id;
                    Db::name("inorder_goods")->insert($in_goods_data);
                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['code'=>0,"msg"=>'网络延时,稍后姿势']);
            }

            return json(['code'=>1,'msg'=>'添加成功']);
        }
        $in_id = input("id");

        //查看所有未完成入库采购单
        $order[] = Db::name("inorder")->where("id",$in_id)->field("sn as order_sn")->find();
        foreach ($order as &$v) {
            $goods =  Db::name("inorder_goods")->where("inorder_id",$in_id)->select();

            foreach($goods as &$m){
                $info = Db::name("goods")->where("id",$m['gid'])->find();
                $p_goods = Db::name("procure_goods")->where("id",$m['pg_id'])->find();
                $m['ware'] = Db::name("warehouse")->where("id",$p_goods['ware_id'])->find()['name'];
                $m['unit'] = $info['unit'];
                $m['name'] = $info['name'];
                $m['specs'] = $info['specs'];
            }
            $v['goods'] = $goods;
        }
//        dump($order);
        //选择供应商
        $gongying = Db::name("gongying")->where("if_del",0)->where("status",1)->select();
        $sn = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        $this->assign('sn',$sn);
        $this->assign("gongying",$gongying);
        $this->assign("order",$order);

        return $this->fetch("changegoods");
    }
    public function changeOrder(){
        $id = input("id");
        $status = input("status");
        Db::startTrans();
        try{
            Db::name("inorder")->where('id',$id)->update(['status'=>$status,'intime'=>time()]);
            //查看该入库单所有的商品
            $goods = Db::name("inorder_goods")->where("inorder_id",$id)->select();
            //增加仓库库存
            foreach($goods as $key=>$val){
                //查询长谷是否有该商品
                $ware_goods = Db::name("ware_goods")->where("gid",$val['gid'])->where("wid",$val["ware_id"])->find();
                if($ware_goods){
                    Db::name("ware_goods")->where("id",$ware_goods['id'])->setInc("num",$val["num"]);
                }else{
                    $data_goods['name'] = Db::name("goods")->where('id',$val['gid'])->field("name")->find()['name'];
                    $data_goods['num'] = $val['num'];
                    $data_goods['add_time'] = time();
                    $data_goods['gid'] = $val['gid'];
                    $data_goods['wid'] = $val["ware_id"];
                    Db::name("ware_goods")->insert($data_goods);
                }
            }

        }catch (\Exception $e){
            Db::rollback();
            return json(['code'=>0,"msg"=>'网络延时,稍后姿势']);
        }
        return json(["code"=>1,"msg"=>"入库完成"]);
    }
    public function del(){
        $id = input("id");
        //查询入库单商品
        $goods = Db::name("inorder_goods")->where("inorder_id",$id)->select();
        //开启事务
        Db::startTrans();
        try{
            //退还商品
            foreach($goods as $key=>$val){
                Db::name("procure_goods")->where("id",$val["pg_id"])->setInc("innum",$val['num']);
            }
            //作废入库单
            $in_order = Db::name("inorder")->where("id",$id)->update(["status"=>0]);

        }catch (\Exception $e){
            Db::rollback();
            return json(['code'=>0,"msg"=>'网络延时,稍后姿势']);
        }
        return json(["code"=>1,"msg"=>'变更成功']);
    }
    public function order(){
        $id = input("id");
        $order = Db::name('inorder')->where('id',$id)->find();
        $goods = Db::name("inorder_goods")->where('inorder_id',$id)->select();
        //查看供应商
        $c_name = Db::name("gongying")->where("id",$order['cid'])->find()['name'];
//        dump($goods);die;
        $goods_ary = [];
        $zong = 0;
        foreach($goods as $key=>$val){
            $goods_ary[$key] =Db::name('goods')->where('id',$val['gid'])->find();
            $goods_ary[$key]['num'] =$val['num'];
            $goods_ary[$key]['inprice'] = $val['inprice'];
            $goods_ary[$key]["ware"] = Db::name('warehouse')->where('id',$val['ware_id'])->field("name")->find()['name'];
            $zong += $val['num'] *$val['inprice'];
        }
        $this->assign("order",$order);
        $this->assign('goods',$goods_ary);
        $this->assign("zong",$zong);

        $daxie = $this->convertAmountToCn($zong,0);
        $this->assign("daxie",$daxie);
        $this->assign("title",'门店自采入库单');
        $this->assign("admin",$this->admin['rel_name']);
        $this->assign("cname",$c_name);
        return $this->fetch();
    }
    public function convertAmountToCn($amount, $type = 1)
    {
        // 判断输出的金额是否为数字或数字字符串
        if (!is_numeric($amount)) {
            return "要转换的金额只能为数字!";
        }

        // 金额为0,则直接输出"零元整"
        if ($amount == 0) {
            return "人民币零元整";
        }

        // 金额不能为负数
        if ($amount < 0) {
            return "要转换的金额不能为负数!";
        }
        // 将金额的数值字符串拆分成数组
        $amountArr = explode('.', $amount);
        if (count($amountArr) > 1) {

            if (strlen($amountArr[1]) >= 3) {
                return '要转换的金额最小为分';
            }
        }

        // 金额不能超过万亿,即12位
        if (strlen($amount) > 12) {
            return "要转换的金额不能为万亿及更高金额!";
        }

        // 预定义中文转换的数组
        $digital = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
        // 预定义单位转换的数组
        $position = array('仟', '佰', '拾', '亿', '仟', '佰', '拾', '万', '仟', '佰', '拾', '元');


        // 将整数位的数值字符串拆分成数组
        $integerArr = str_split($amountArr[0], 1);

        // 将整数部分替换成大写汉字
        $result = '';
        $integerArrLength = count($integerArr);     // 整数位数组的长度
        $positionLength = count($position);         // 单位数组的长度
        for ($i = 0; $i < $integerArrLength; $i++) {
            // 如果数值不为0,则正常转换
            if ($integerArr[$i] != 0) {
                $result = $result . $digital[$integerArr[$i]] . $position[$positionLength - $integerArrLength + $i];
            } else {
                // 如果数值为0, 且单位是亿,万,元这三个的时候,则直接显示单位
                if (($positionLength - $integerArrLength + $i + 1) % 4 == 0) {
                    $result = $result . $position[$positionLength - $integerArrLength + $i];
                }
            }
        }

        // 如果小数位也要转换
        if ($type == 0) {
            // 将小数位的数值字符串拆分成数组
            if (count($amountArr) > 1) {
                $decimalArr = str_split($amountArr[1], 1);
                // 将角替换成大写汉字. 如果为0,则不替换
                if ($decimalArr[0] != 0) {
                    $result = $result . $digital[$decimalArr[0]] . '角';
                }
                if (count($decimalArr) > 1) {
                    // 将分替换成大写汉字. 如果为0,则不替换
                    if ($decimalArr[1] != 0) {
                        $result = $result . $digital[$decimalArr[1]] . '分';
                    }
                }

            }
        } else {
            $result = $result . '整';
        }
        return $result;
    }

}